<template>
  <div class="app-container">
    <!-- 左侧对话历史 -->
    <div class="chat-history-sidebar">
      <div class="sidebar-header">
        <h2>对话历史</h2>
        <button 
          class="new-chat-button" 
          @click="handleNewChat"
          title="新建对话"
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
            <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
          </svg>
          新对话
        </button>
      </div>
      
      <div class="history-list">
        <div 
          v-for="(message, index) in chatHistoryItems" 
          :key="index"
          class="history-item"
          @click="handleSelectHistoryItem(index)"
        >
          <div class="history-item-content">{{ message.content }}</div>
          <div class="history-item-time">{{ formatTime(message.timestamp) }}</div>
        </div>
        
        <div v-if="chatHistoryItems.length === 0" class="empty-history">
          <p>暂无对话历史</p>
        </div>
      </div>
    </div>
    
    <!-- 右侧聊天区域 -->
    <div class="chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <h1>AI 聊天助手</h1>
      <div class="session-info" v-if="chatStore.currentSessionId">
        会话ID: {{ chatStore.currentSessionId }}
      </div>
      <div class="header-actions">
        <button 
          class="clear-button" 
          @click="handleClearChat"
          :disabled="!chatStore.hasMessages"
          title="清空聊天"
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
            <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
          </svg>
        </button>
      </div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesRef">
      <!-- 欢迎消息 -->
      <div v-if="!chatStore.hasMessages" class="welcome-message">
        <div class="welcome-content">
          <h2>👋 欢迎使用AI聊天助手</h2>
          <p>我可以帮助您解答问题、进行对话交流。请输入您的问题开始对话！</p>
          <div class="welcome-features">
            <div class="feature-item">
              <span class="feature-icon">💭</span>
              <span>实时思考，过程展示</span>
            </div>
            <div class="feature-item">
              <span class="feature-icon">⚡</span>
              <span>流式响应，即时反馈</span>
            </div>
            <div class="feature-item">
              <span class="feature-icon">🎯</span>
              <span>智能对话，精准回答</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 聊天消息 -->
      <ChatMessage
        v-for="message in chatStore.messages"
        :key="message.id"
        :message="message"
        :enable-typewriter="false"
      />

      <!-- 正在输入指示器 -->
      <div v-if="chatStore.isLoading && !hasStreamingMessage" class="typing-indicator">
        <div class="message-avatar">AI</div>
        <div class="typing-content">
          <span>正在连接...</span>
          <div class="typing-dots">
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
            <div class="typing-dot"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-if="chatStore.error" class="error-message">
      <div class="error-content">
        <span class="error-icon">❌</span>
        <span class="error-text">{{ chatStore.error }}</span>
        <button @click="chatStore.error = null" class="error-close" title="关闭错误提示">×</button>
      </div>
    </div>

    <!-- 聊天输入区域 -->
    <ChatInput 
      :is-loading="chatStore.isLoading"
      @send="handleSendMessage"
      @stop="handleStopStreaming"
      ref="chatInputRef"
    />
    
    <!-- 流式数据调试器 -->
    <StreamDebugger 
      v-if="isDevelopment"
      :enabled="false"
      ref="debuggerRef"
    />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useChatStore } from './stores/chat'
import ChatMessage from './components/ChatMessage.vue'
import ChatInput from './components/ChatInput.vue'
import StreamDebugger from './components/StreamDebugger.vue'

const chatStore = useChatStore()
const messagesRef = ref(null)
const chatInputRef = ref(null)
const debuggerRef = ref(null)

// 开发模式下启用调试器
const isDevelopment = import.meta.env.DEV

// 检查是否有正在流式传输的消息
const hasStreamingMessage = computed(() => {
  return chatStore.messages.some(msg => msg.isStreaming)
})

// 对话历史项目
const chatHistoryItems = computed(() => {
  // 只获取用户发送的消息作为历史记录
  return chatStore.messages.filter(msg => msg.role === 'user')
})

// 发送消息
const handleSendMessage = async (message) => {
  try {
    // 记录开始日志
    if (debuggerRef.value) {
      debuggerRef.value.logStreamStart(chatStore.currentSessionId)
    }
    
    await chatStore.sendMessage(message, {
      onChunk: (chunk) => {
        // 记录数据块日志
        if (debuggerRef.value) {
          debuggerRef.value.logStreamChunk(chunk)
        }
      },
      onComplete: (finalData) => {
        // 记录完成日志
        if (debuggerRef.value) {
          debuggerRef.value.logStreamComplete(finalData)
        }
      },
      onError: (error) => {
        // 记录错误日志
        if (debuggerRef.value) {
          debuggerRef.value.logStreamError(error)
        }
      }
    })
    scrollToBottom()
  } catch (error) {
    console.error('发送消息失败:', error)
    if (debuggerRef.value) {
      debuggerRef.value.logStreamError(error)
    }
  }
}

// 停止流式响应
const handleStopStreaming = () => {
  chatStore.stopStreaming()
}

// 清空聊天
const handleClearChat = () => {
  if (confirm('确定要清空所有聊天记录吗？')) {
    chatStore.clearChat()
    chatInputRef.value?.focus()
  }
}

// 新建对话
const handleNewChat = () => {
  chatStore.clearChat()
  chatStore.initSession()
  chatInputRef.value?.focus()
}

// 选择历史对话项
const handleSelectHistoryItem = (index) => {
  const message = chatHistoryItems.value[index]
  if (message) {
    // 找到原始消息在完整消息列表中的索引
    const originalIndex = chatStore.messages.findIndex(msg => msg.id === message.id)
    if (originalIndex >= 0) {
      // 滚动到该消息
      scrollToMessage(originalIndex)
    }
  }
}

// 滚动到指定消息
const scrollToMessage = (index) => {
  nextTick(() => {
    const messageElements = messagesRef.value.querySelectorAll('.message')
    if (messageElements[index]) {
      messageElements[index].scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  })
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) {
    return '刚刚'
  } else if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight
  }
}

// 平滑滚动到底部
const smoothScrollToBottom = async () => {
  await nextTick()
  if (messagesRef.value) {
    messagesRef.value.scrollTo({
      top: messagesRef.value.scrollHeight,
      behavior: 'smooth'
    })
  }
}

// 监听消息变化，自动滚动到底部
watch(() => chatStore.messages.length, () => {
  scrollToBottom()
})

// 监听流式消息内容变化，平滑滚动
watch(() => {
  const streamingMsg = chatStore.messages.find(msg => msg.isStreaming)
  return streamingMsg ? streamingMsg.content : null
}, (newContent, oldContent) => {
  if (newContent && newContent !== oldContent) {
    // 只有在内容增加时才滚动
    if (!oldContent || newContent.length > oldContent.length) {
      smoothScrollToBottom()
    }
  }
})

// 组件挂载后初始化
onMounted(() => {
  chatStore.initSession()
  chatInputRef.value?.focus()
})
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.chat-history-sidebar {
  width: 280px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-right: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  flex-direction: column;
  height: 100%;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
}

.sidebar-header {
  padding: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.1);
}

.sidebar-header h2 {
  margin: 0;
  font-size: 1.1em;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.new-chat-button {
  display: flex;
  align-items: center;
  gap: 6px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 0;
  padding: 6px 12px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.new-chat-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}

.history-item {
  padding: 12px;
  border-radius: 0;
  margin-bottom: 10px;
  background: rgba(255, 255, 255, 0.7);
  cursor: pointer;
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.history-item:hover {
  background: rgba(255, 255, 255, 0.9);
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.history-item-content {
  font-size: 13px;
  color: #495057;
  margin-bottom: 6px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
}

.history-item-time {
  font-size: 11px;
  color: #7986cb;
  display: flex;
  align-items: center;
}

.history-item-time::before {
  content: "";
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #7986cb;
  margin-right: 6px;
}

.empty-history {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #7986cb;
  font-size: 14px;
  text-align: center;
}

.empty-history::before {
  content: "💬";
  font-size: 32px;
  margin-bottom: 16px;
  opacity: 0.7;
}

.chat-container {
  display: flex;
  flex-direction: column;
  flex: 1;
  height: 100vh;
  max-width: calc(100% - 280px);
  width: 100%;
  background: #ffffff;
  border-radius: 0;
}

.chat-header {
  background: #ffffff;
  padding: 15px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.chat-header h1 {
  margin: 0;
  font-size: 1.2em;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.session-info {
  font-size: 12px;
  color: #6c757d;
  background: rgba(108, 117, 125, 0.1);
  padding: 4px 8px;
  border-radius: 0;
  font-family: monospace;
}

.header-actions {
  position: absolute;
  right: 20px;
  top: 50%;
  transform: translateY(-50%);
}

.clear-button {
  background: rgba(108, 117, 125, 0.1);
  border: none;
  border-radius: 0;
  color: #6c757d;
  padding: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.clear-button:hover:not(:disabled) {
  background: rgba(108, 117, 125, 0.2);
  color: #495057;
  transform: scale(1.05);
}

.clear-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  background: transparent;
  scroll-behavior: smooth;
  width: 100%;
  max-width: 100%;
  border-radius: 0;
}

.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.welcome-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  text-align: center;
  padding: 40px 20px;
}

.welcome-content {
  max-width: 600px;
}

.welcome-content h2 {
  color: #333;
  margin-bottom: 12px;
  font-size: 1.5em;
  font-weight: 600;
}

.welcome-content p {
  color: #666;
  line-height: 1.5;
  margin-bottom: 24px;
  font-size: 0.95em;
}

.welcome-features {
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: center;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 15px;
  background: rgba(102, 126, 234, 0.1);
  border-radius: 0;
  color: #495057;
  font-weight: 500;
  min-width: 180px;
  font-size: 0.9em;
}

.feature-icon {
  font-size: 1.2em;
}

.typing-indicator {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px 20px;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.typing-indicator .message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  flex-shrink: 0;
}

.typing-content {
  background: #f1f3f4;
  padding: 12px 16px;
  border-radius: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dot {
  width: 6px;
  height: 6px;
  background: #666;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-dot:nth-child(1) { animation-delay: -0.32s; }
.typing-dot:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.error-message {
  background: linear-gradient(135deg, #fee 0%, #fdd 100%);
  border-top: 1px solid #fcc;
  padding: 12px 20px;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from { transform: translateY(-100%); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

.error-content {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #c33;
  font-size: 14px;
}

.error-icon {
  flex-shrink: 0;
}

.error-text {
  flex: 1;
  font-weight: 500;
}

.error-close {
  background: none;
  border: none;
  color: #c33;
  font-size: 18px;
  cursor: pointer;
  padding: 4px;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0;
  transition: background-color 0.2s;
}

.error-close:hover {
  background: rgba(204, 51, 51, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    flex-direction: column;
  }
  
  .chat-history-sidebar {
    width: 100%;
    height: auto;
    max-height: 35vh;
    border-right: none;
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  }
  
  .chat-container {
    height: 65vh;
    max-width: 100%;
  }
  
  .chat-header {
    padding: 12px 16px;
  }
  
  .chat-header h1 {
    font-size: 1.3em;
  }
  
  .welcome-content {
    max-width: 90%;
    padding: 20px;
  }
  
  .welcome-content h2 {
    font-size: 1.5em;
  }
  
  .welcome-content p {
    font-size: 1em;
  }
  
  .welcome-features {
    gap: 12px;
  }
  
  .feature-item {
    padding: 10px 16px;
    min-width: auto;
    width: 100%;
  }
  
  .typing-indicator {
    padding: 12px 16px;
    gap: 10px;
  }
  
  .typing-indicator .message-avatar {
    width: 36px;
    height: 36px;
  }
  
  .error-message {
    padding: 10px 16px;
  }
}

/* 暗色主题支持 */
@media (prefers-color-scheme: dark) {
  .chat-messages {
    background: #1a1a1a;
  }
  
  .welcome-content h2 {
    color: #e9ecef;
  }
  
  .welcome-content p {
    color: #adb5bd;
  }
  
  .feature-item {
    background: rgba(102, 126, 234, 0.2);
    color: #e9ecef;
  }
}
</style>